package com.heima.article.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.article.mapper.ApArticleConfigMapper;
import com.heima.article.mapper.ApArticleContentMapper;
import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.ApArticleConfigService;
import com.heima.article.service.ApArticleContentService;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.GeneratePageService;
import com.heima.common.constants.ArticleConstants;
import com.heima.common.constants.WemediaConstants;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.exception.CustException;
import com.heima.common.result.ResponseResult;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.dto.ArticleHomeDTO;
import com.heima.model.article.dto.ArticleInfoDto;
import com.heima.model.article.pojo.ApArticle;
import com.heima.model.article.pojo.ApArticleConfig;
import com.heima.model.article.pojo.ApArticleContent;
import com.heima.model.user.pojo.ApUser;
import com.heima.model.wemedia.pojo.WmNews;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements ApArticleService {
    @Autowired
    WemediaFeign wemediaFeign;
    @Autowired
    ApArticleConfigService apArticleConfigService;
    @Autowired
    ApArticleContentService apArticleContentService;
    @Resource
    ApArticleMapper apArticleMapper;
    @Autowired
    GeneratePageService generatePageService;
    @Resource
    ApArticleConfigMapper apArticleConfigMapper;
    @Resource
    ApArticleContentMapper apArticleContentMapper;
    @Value("${file.oss.web-site}")
    String fileServerUrl;
    /**
     * wmNews  查询
     * ap_article   ap_article_confg   ap_article_content  保存3表数据
     * wmNews  修改  9  article_id
     * @param newsId 文章id
     */
    @Transactional(rollbackFor = Exception.class,timeout = 180000)
    @Override
    public void publishArticle(Integer newsId) {
        // 1. 根据文章id 查询自媒体文章信息
        WmNews wmNews = getWmNews(newsId);
        // 2. 根据wmNews信息封装ApArticle对象
        ApArticle article = parseApArticle(wmNews);
        // 3. 保存或修改apArticle对象
        saveOrUpdateApArticle(article);
        // 4. 保存配置信息 和 内容信息
        saveConfigAndContent(article,wmNews);
//         5. 页面静态化
//        generatePageService.generateArticlePage(wmNews.getContent(),article);
        // 6. 修改WmNews的状态，将状态改为 9 并设置关联的articleId
        updateWmNews(wmNews,article);
    }
    /**
     * 修改文章为上架  发布状态
     * @param wmNews
     * @param article
     */
    private void updateWmNews(WmNews wmNews, ApArticle article) {
        wmNews.setStatus(WemediaConstants.WM_NEWS_PUBLISH_STATUS);
        wmNews.setEnable(WemediaConstants.WM_NEWS_UP);
        wmNews.setArticleId(article.getId());
        wemediaFeign.updateWmNews(wmNews);
    }
    /**
     * app列表页面查询文章列表
     * @param loadtype 0为加载更多  1为加载最新
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(Integer loadtype, ArticleHomeDTO dto) {
        // 1. 校验参数
        Integer size = dto.getSize();
        if(size==null || size<=0){
            dto.setSize(10);
        }
        if(StringUtils.isBlank(dto.getTag())){
            // 推荐频道
            dto.setTag(ArticleConstants.DEFAULT_TAG);
        }
        if (dto.getMinBehotTime()==null) {
            dto.setMinBehotTime(new Date());
        }
        if (dto.getMaxBehotTime()==null) {
            dto.setMaxBehotTime(new Date());
        }
        if (!ArticleConstants.LOADTYPE_LOAD_MORE.equals(loadtype)&&!ArticleConstants.LOADTYPE_LOAD_NEW.equals(loadtype)) {
            loadtype = ArticleConstants.LOADTYPE_LOAD_MORE;
        }
        // 3. 封装返回结果
        return ResponseResult.okResult(apArticleMapper.loadArticleList(dto, loadtype));
    }
    private void saveConfigAndContent(ApArticle article, WmNews wmNews) {
        // 1. 保存文章配置信息
        ApArticleConfig config = new ApArticleConfig();
        config.setArticleId(article.getId());
        config.setIsComment(true);// 是否允许评论
        config.setIsForward(true);//// 是否允许 转发
        config.setIsDown(false);// 是否下架
        config.setIsDelete(false);// 是否删除
        apArticleConfigService.save(config);
        // 2. 保存文章内容信息
        ApArticleContent content = new ApArticleContent();
        content.setArticleId(article.getId());
        content.setContent(wmNews.getContent());
        apArticleContentService.save(content);
    }
    private void saveOrUpdateApArticle(ApArticle article) {
        if(article.getId()==null){
            // 保存
            this.save(article);
        }else {
            // 删除关联的 文章配置信息  和  文章详情信息
            apArticleConfigService.remove(
                    Wrappers.<ApArticleConfig>lambdaQuery()
                            .eq(ApArticleConfig::getArticleId,article.getId())
            );
            apArticleContentService.remove(
                    Wrappers.<ApArticleContent>lambdaQuery()
                            .eq(ApArticleContent::getArticleId,article.getId())
            );
            // 修改
            this.updateById(article);
        }
    }
    /**
     * 基于wmNews 封装 ApArticle
     * @param wmNews
     * @return
     */
    private ApArticle parseApArticle(WmNews wmNews) {
        // 1. 创建article ,将wmNews的同名属性拷贝进去
        ApArticle article = new ApArticle();
        BeanUtils.copyProperties(wmNews,article);
        // 2. 单独设置articleId字段
        article.setId(wmNews.getArticleId());
        // 3. 其它需要补充字段  flag  layout
        article.setLayout(wmNews.getType());
        article.setAuthorId(wmNews.getUserId());
        return article  ;
    }
    private WmNews getWmNews(Integer newsId) {
        // 1. 根据id使用feign接口远程查询
        ResponseResult<WmNews> result = wemediaFeign.findWmNewsById(newsId);
        WmNews wmNews = result.getData();
        // 2. 判断文章是否为null
        if (wmNews ==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"文章不存在");
        }
        // 3. 判断文章的状态 必须是  4 或 8
        Integer status = wmNews.getStatus();
        if (!WemediaConstants.WM_NEWS_AUTH_PASS.equals(status)&&!WemediaConstants.WM_NEWS_AUTHED_STATUS.equals(status)) {
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"文章的状态 不是审核通过状态，发布文章失败");
        }
        return wmNews;
    }
    @Override
    public ResponseResult loadArticleInfo(ArticleInfoDto dto) {
        Map<String,Object> resultMap = new HashMap<>();
        // 1. 检查参数
        if(dto == null || dto.getArticleId() == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        // 2. 查询配置信息
        ApArticleConfig config = apArticleConfigMapper.selectOne(
                Wrappers.<ApArticleConfig>lambdaQuery()
                        .eq(ApArticleConfig::getArticleId, dto.getArticleId())
        );
        // 3. 查询文章内容信息
        if(config == null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if(!config.getIsDown()&&!config.getIsDelete()){
            ApArticleContent content = apArticleContentMapper.selectOne(
                    Wrappers.<ApArticleContent>lambdaQuery()
                            .eq(ApArticleContent::getArticleId, dto.getArticleId())
            );
            // 给文章详情内容添加图片前缀路径
            resultMap.put("content",content);
        }
        // 4. 将配置和内容都返回到前端   content   config
        resultMap.put("config",config);
        ResponseResult responseResult = ResponseResult.okResult(resultMap);
        responseResult.setHost(fileServerUrl);
        return responseResult;
    }

    @Override
    public ResponseResult loadArticleBehavior(ArticleInfoDto dto) {
        return null;
    }


}